<template>
  <div class="w-full h-full flex justify-center items-center bg-blue-400">
    <div>
      <div class="text-4xl text-center p-5 font-bold text-white">注册</div>
      <div class="p-5 bg-white rounded-md">
        <v-sheet class="mx-auto" width="300">
          <v-form fast-fail @submit="toRegister">
            <v-text-field
              v-model="form.username"
              :rules="[valRequired('用户名')]"
              label="用户名"
            ></v-text-field>
            <v-text-field
              v-model="form.password"
              :rules="[valRequired('密码')]"
              label="密码"
              required
            ></v-text-field>
            <v-select
              v-model="form.sex"
              :items="[
                { name: '男', val: '1' },
                { name: '女', val: '2' },
              ]"
              item-title="name"
              item-value="val"
              label="性别"
              required
            />
            <v-btn class="mt-2" type="submit" block>提交</v-btn>
          </v-form>
        </v-sheet>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { register } from "@/api";
import { ref } from "vue";
import { useRouter } from "vue-router";

const router = useRouter();

const form = ref({
  username: "",
  password: "",
  sex: "1",
});

const toRegister = async (event: Promise<{ valid: boolean }>) => {
  // 异步校验
  let validate = await event;
  // 发起注册请求
  if (validate.valid) {
    register(form.value);
    router.push("/");
  }
};

// 校验规则：必填
const valRequired = (key: string) => (v: string) => !!v || `${key}必填！`;
</script>
